package main

import (
	"encoding/json"
	"fmt"
	"github.com/nats-io/go-nats"
	"github.com/pborman/uuid"
	"log"
	"time"
)

const (
	//url   = "nats://192.168.3.125:4222"
	ClientNatUrl    = nats.DefaultURL
	ProductInfoSubj = "product_info_subj"
)

var (
	encodeConnClient *nats.EncodedConn
	connClient       *nats.Conn
	clientErr        error
)

func init() {
	if connClient, clientErr = nats.Connect(ClientNatUrl); clientErr != nil {
		fmt.Println("初始化错误：", clientErr)
	} else {
		if encodeConnClient, clientErr = nats.NewEncodedConn(connClient, nats.JSON_ENCODER); clientErr != nil {
			if clientErr != nil {
				log.Fatal("初始化encodeConn失败：", clientErr)
			}
		}
	}
}

// h
func main() {
	// 推送基础包数据
	SendBaseData()

}

type BaseData struct {
	Name string
	Age  int64
	High int64
}

//消息推送
func ClientSendMsgToServerByRequest(subj, data string) {
	id := uuid.New()
	//clientErr := connClient.Publish(subj, []byte(id+":" + data))
	//if clientErr != nil{
	//	fmt.Println("消息推送失败：", clientErr)
	//}else {
	//	_, clientErr = connClient.Subscribe(subj, func(msg *nats.Msg) {
	//		if clientErr != nil{
	//			fmt.Println("收到的reply失败：", clientErr)
	//		}else {
	//			fmt.Println("成功收到的reply消息为:", string(msg.Data))
	//		}
	//	})
	//}

	if msg, err := connClient.Request(subj, []byte(id+" hello"), time.Second); checkErr(err, func() {
		// handle err
	}) {
		log.Println(string(msg.Data)) // eyJOYW1lIjoiaGloaSIsIkFnZSI6MTIsIkhpZ2giOjE3MH0=
		repRls := new(BaseData)
		err = encodeConnClient.Enc.Decode(msg.Subject, msg.Data, repRls)
		if err != nil {
			fmt.Println("encodeConnClient.Enc.Decode err:", err)
		} else {
			fmt.Println(repRls)
		}
	}

}

/*
客户端的推送
./main -port=client -subj=weather -data=hello world
*/
func SendBaseData() {
	subj := ProductInfoSubj
	data := new(BaseData)
	data.Name = "James"
	data.Age = 24
	data.High = 187

	dataStr, err := json.Marshal(data)
	if err != nil {
		log.Fatal("json数据转化成为str：", err)
	}
	ClientSendMsgToServerByRequest(subj, string(dataStr))
}

func checkErr(err error, errFun func()) bool {
	if err != nil {
		log.Println(err)
		errFun()
		return false
	}
	return true
}
